﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;
using System.Text;

namespace Core.Web.Api.Utils.Init
{
    public static class InitJWTAuthentication
    {
        /// <summary>
        /// 使用JWT
        /// </summary>
        /// <param name="services"></param>
        public static void UseJWTAuthentication(this IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                ;

            }).AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    SaveSigninToken = true,//保存token,后台验证token是否生效(重要)
                    ValidateIssuer = true,//是否验证Issuer
                    ValidateAudience = true,//是否验证Audience
                    ValidateLifetime = true,//是否验证失效时间
                    ValidateIssuerSigningKey = true,//是否验证SecurityKey
                    ValidAudience = APIConfig.JwtOption.Audience,//Audience
                    ValidIssuer = APIConfig.JwtOption.Issuer,//Issuer，这两项和前面签发jwt的设置一致
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(APIConfig.JwtOption.Secret)),
                    AudienceValidator = (IEnumerable<string> audiences, SecurityToken securityToken,
                    TokenValidationParameters validationParameters) =>
                    {
                        bool audienceValidator = true;
                        return audienceValidator;
                    }
                    //ValidateIssuerSigningKey = true,
                    //IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(APIConfig.JwtOption.Secret)),//秘钥
                    //ValidateIssuer = true,
                    //ValidIssuer = APIConfig.JwtOption.Issuer,
                    //ValidateAudience = true,
                    //ValidAudience = APIConfig.JwtOption.Audience,
                    //ValidateLifetime = true,
                    //ClockSkew = TimeSpan.FromMinutes(5)
                };
            });
        }
    }
}
